// import { resolve } from './C:/Users/hzhb/AppData/Local/Microsoft/TypeScript/2.6/node_modules/@types/bluebird';
// import { reject } from './C:/Users/hzhb/AppData/Local/Microsoft/TypeScript/2.6/node_modules/@types/bluebird';

const http = require('http')
const qs=require('querystring')
const config = require('../config')

const clicksnum = async (ctx,next) => {  //请求点击量
    let postdata=qs.stringify(ctx.request.body)
    const result = new Promise((resolve,reject) => {
        let opt = {
            hostname: config.hostname,
            port: config.port,
            path: `/yesClicks/clicks?${postdata}`,
            method: 'POST',
            headers:{
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': postdata.length
            }
        }
        let req = http.request(opt,(res) => {
            res.setEncoding('utf8')
            let resdata=''
            res.on('data',(chunk) => {
                resdata+=chunk
            })
            res.on('end',() => {
                if(resdata){
                    resolve(JSON.parse(resdata))
                }else{
                    resolve([]) 
                }
            })
        })
        req.on('errer',(e) => {
            reject(e)
        })
        req.write(postdata)
        req.end()
    })
    let data = await result
    if(data.code){
        ctx.error(data)
    }else{
        ctx.success(data)
    }
}

const getselectclick = async (ctx,next) => {  //热门访问
    const result = new Promise((resolve,reject) => {
        let opt = {
            hostname: config.hostname,
            port: config.port,
            path: '/yesClicks/selectClicks?p=1&s=10',
            method: 'GET'
        }
        let req = http.request(opt,(res) => {
            res.setEncoding('utf8')
            let resdata=''
            res.on('data',(chunk) => {
                resdata += chunk
            })
            res.on('end',() => {
                resolve(JSON.parse(resdata))
            })
        })
        req.on('error',(e) => {
            reject(e)
        })
        req.end()
    })
    let data = await result
    if(data.code){
        ctx.error(data)
    }else{
        ctx.success(data)
    }
}

module.exports={
    clicksnum,
    getselectclick
}